<template>
  <div id="mapscene" ref="mapscene"></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { mapUrl, whiteModel, lxmMOdelIdUrl, lxmStreetLineUrl } from '@/utils/config'
// import { findNearScale } from '@/utils/map'
// import { PolylineTrailLinkMaterialProperty } from '@/utils/myCesium'
import axios from 'axios'
let mapscene = ref(null)
const centerList = []
onMounted(() => {
  initMap()
})
onBeforeUnmount(() => {
  window.viewer.destroy()
  window.viewer.jMap = null
})
const initMap = () => {
  window.viewer = new SuperMap3D.Viewer('mapscene', {
    contextOptions: {
      maxDrawingBufferWidth: 1920 * 4,
      maxDrawingBufferHeight: 2160
    }
  })
  viewer.scene.screenSpaceCameraController.maximumZoomDistance = 10000
  viewer.imageryLayers.removeAll()
  viewer.scene.globe.showGroundAtmosphere = false
  viewer.scene.globe.baseColor = SuperMap3D.Color.TRANSPARENT
  viewer.scene.skyAtmosphere.show = false
  viewer.scene.fog.enable = false
  viewer.scene.sun.show = false //在Cesium1.6(不确定)之后的版本会显示太阳和月亮，不关闭会影响展示
  viewer.scene.moon.show = false
  viewer.scene.skyBox.show = false //关闭天空盒，否则会显示天空颜色
  // viewer.scene.globe.depthTestAgainstTerrain = false
  if (SuperMap3D.FeatureDetection.supportsImageRenderingPixelated()) {
    //判断是否支持图像渲染像素化处理
    viewer.resolutionScale = window.devicePixelRatio
  }

  //抗锯齿
  viewer.scene.fxaa = true
  viewer.scene.postProcessStages.fxaa.enabled = true

  let layer = new SuperMap3D.SuperMapImageryProvider({
    url: mapUrl //影像服务的地址
  })
  let imgLayer = viewer.imageryLayers.addImageryProvider(layer)
  initModel()
  initStreetLine()
  // function get84Cood(positon) {
  //   let zb = SuperMap3D.Cartographic.fromCartesian(positon)
  //   let lat = SuperMap3D.Math.toDegrees(zb.latitude)
  //   let lon = SuperMap3D.Math.toDegrees(zb.longitude)
  //   let height = zb.height
  //   return {
  //     lon,
  //     lat,
  //     height
  //   }
  // }
  // //获取相机参数
  // function getCamera(viewer) {
  //   let p = get84Cood(viewer.camera.position)
  //   let position = [p.lon, p.lat, p.height]
  //   console.log(position, viewer.camera.heading, viewer.camera.pitch, viewer.camera.roll)
  //   return {
  //     position,
  //     heading: viewer.camera.heading,
  //     pitch: viewer.camera.pitch,
  //     roll: viewer.camera.roll
  //   }
  // }
  // viewer.scene.camera.moveEnd.addEventListener(function () {
  //   getCamera(viewer)
  // })
  // SuperMap3D.loadJson('./json/LXM_features.geojson')
  //   .then(function (jsonData) {
  //     // Do something with the JSON object
  //     console.log(jsonData)
  //     viewer.dataSources.add(jsonData).then((data) => {
  //       console.log('加载路网返回的数据', data)
  //     })
  //   })
  //   .otherwise(function (error) {
  //     // an error occurred
  //   })
}
// 初始化白膜
const initModel = async () => {
  const queryParams = {
    getFeatureMode: 'SQL',
    datasetNames: ['BM:建筑物'],
    maxFeatures: 5000,
    hasGeometry: false,
    queryParameter: {
      sortClause: null,
      ids: null,
      name: null,
      attributeFilter: "街镇 = '老西门街道'",
      groupClause: null,
      linkItems: null,
      joinItems: null,
      fields: null
    }
  }

  const result = await axios.post(lxmMOdelIdUrl + '?returnContent=true', queryParams)
  const showIds = result.data.features.map((item) => item.fieldValues[0])
  let model = viewer.scene.open(whiteModel)
  model.then(function (layers) {
    viewer.camera.setView({
      destination: SuperMap3D.Cartesian3.fromDegrees(
        121.48830428493527,
        31.194448035864237,
        3172.518900550351
      ),
      orientation: {
        heading: 6.117389013987249, // east, default value is 0.0 (north)
        pitch: -0.8695790901944287, // default value (looking down)
        roll: 2.0473625195194245e-7 // default value
      }
    })
    let hypsometricSetting = new SuperMap3D.HypsometricSetting()
    hypsometricSetting.MinVisibleValue = 0
    hypsometricSetting.MaxVisibleValue = 130
    let colorTable = new SuperMap3D.ColorTable()
    colorTable.insert(130, new SuperMap3D.Color(0 / 255, 254 / 255, 255 / 255))
    colorTable.insert(108, new SuperMap3D.Color(0 / 255, 254 / 255, 255 / 255))
    colorTable.insert(90, new SuperMap3D.Color(0 / 255, 229 / 255, 255 / 255))
    colorTable.insert(72, new SuperMap3D.Color(0 / 255, 165 / 255, 255 / 255))
    colorTable.insert(36, new SuperMap3D.Color(0 / 255, 119 / 255, 255 / 255))
    colorTable.insert(18, new SuperMap3D.Color(0, 161 / 255, 1))
    colorTable.insert(0, new SuperMap3D.Color(27 / 255, 80 / 255, 133 / 255))
    hypsometricSetting.ColorTable = colorTable
    hypsometricSetting._opacity = 1

    layers[0].hypsometricSetting = {
      hypsometricSetting: hypsometricSetting,
      analysisMode: SuperMap3D.HypsometricSettingEnum.AnalysisRegionMode.ARM_ALL
    }
    layers[0].setObjsVisible(showIds, true)
  })
}
// 初始化街道线
const initStreetLine = async () => {
  const queryParams = {
    getFeatureMode: 'SQL',
    datasetNames: ['173.82.57.1_db_hp2019:村居委会'],
    maxFeatures: 5000,
    hasGeometry: true,
    queryParameter: {
      sortClause: null,
      ids: null,
      name: null,
      attributeFilter: "所属街道='老西门街道'",
      groupClause: null,
      linkItems: null,
      joinItems: null,
      fields: null
    }
  }

  const result = await axios.post(lxmStreetLineUrl + '?returnContent=true', queryParams)
  result.data.features.forEach((point) => {
    const linePoints = []
    centerList.push({ name: point.fieldValues[12], center: point.geometry.center })
    point.geometry.points.forEach((item, index) => {
      linePoints.push(item.x)
      linePoints.push(item.y)
    })
    let line = new SuperMap3D.Entity({
      polyline: {
        positions: new SuperMap3D.Cartesian3.fromDegreesArray(linePoints),
        width: 3, //边界线宽
        material: SuperMap3D.Color.fromCssColorString('#52e3dc') //边界线颜色
      }
    })
    viewer.entities.add(line)
  })
  juweiLabel()
}
const juweiLabel = () => {
  centerList.forEach((item, index) => {
    viewer.entities.add({
      position: SuperMap3D.Cartesian3.fromDegrees(item.center.x, item.center.y, 150),
      // 点
      point: {
        color: SuperMap3D.Color.YELLOW, // 点位颜色
        pixelSize: 10, // 像素点大小
        show: false
      },
      // 文字
      label: {
        // 文本。支持显式换行符“ \ n”
        text: item.name,
        // 字体样式，以CSS语法指定字体
        // font: '20pt Source Han Sans CN',
        // 字体颜色
        fillColor: SuperMap3D.Color.WHITE,
        // 背景颜色
        // backgroundColor: SuperMap3D.Color.AQUA,
        // 是否显示背景颜色
        // showBackground: true,
        // 字体边框
        // outline: true,
        // 字体边框颜色
        // outlineColor: SuperMap3D.Color.WHITE,
        // 字体边框尺寸
        // outlineWidth: 10,
        // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
        scale: 1,
        // 设置样式：FILL：填写标签的文本，但不要勾勒轮廓；OUTLINE：概述标签的文本，但不要填写；FILL_AND_OUTLINE：填写并概述标签文本。
        style: SuperMap3D.LabelStyle.FILL,
        // 相对于坐标的水平位置
        verticalOrigin: SuperMap3D.VerticalOrigin.CENTER,
        // 相对于坐标的水平位置
        horizontalOrigin: SuperMap3D.HorizontalOrigin.LEFT,
        // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
        // pixelOffset: new SuperMap3D.Cartesian2(10, 0),
        // 显示在距相机的距离处的属性，多少区间内是可以显示的
        // distanceDisplayCondition: new SuperMap3D.DistanceDisplayCondition(0, 5000),
        // 是否显示
        show: true
      }
    })
  })
}
</script>
<style scoped lang="scss">
#mapscene {
  width: 100%;
  height: 100%;
}
</style>
